<?php

namespace app\api\Service;

use app\common\library\Auth;
use app\common\library\Sms;
use think\Db;
use fast\Random;
use fast\Hashids;
use think\Config;
use think\Validate;
use think\Response;

class UserService
{
    // 账号密码注册
    public static function register($data)
    {
        $auth = Auth::instance();
        $mobile = $data['mobile'];
        $code = $data['code'];
        $password = $data['password'];
        $confirmpw = $data['confirmpw'];
        $invite = isset($data['invite']) ? $data['invite'] : '';

        if( $invite ){
            $pid = \app\admin\model\User::where(['invite'=>$invite])->value('id');
        }else{
            $pid = 0;
        }

        $username = $mobile;
        if (!$username || !$password) {
            return ['code'=>0,'msg'=>'无效参数','data'=>''];
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            return ['code'=>0,'msg'=>'手机号格式不正确','data'=>''];
        }
        $ret = Sms::check($mobile, $code, 'register');
//        $ret = true;
        if (!$ret) {
            return ['code'=>0,'msg'=>'验证码错误','data'=>''];
        }
        if ($password != $confirmpw) {
            return ['code'=>0,'msg'=>'两次密码不一致','data'=>''];
        }
        $invite = generateUniqueNumber();
        $ret = $auth->register($mobile, $password, '', $mobile, 1, ['pid'=>$pid,'invite'=>$invite]);
        if ($ret) {

            // 上级奖励积分
            if( $pid ) {
                $invite_reward = Config::get('site.invite_reward');
                \app\common\model\User::score($invite_reward, $pid, '邀请注册奖励');
            }

            Sms::flush($mobile, 'register');
            $data = $auth->getUserinfo();
            $data['invite'] = $invite;
            return ['code'=>1,'msg'=>'注册成功','data'=>$data];
        } else {
            return ['code'=>0,'msg'=>$auth->getError(),'data'=>''];
        }
    }

    // 账号密码登录
    public static function login($data)
    {
        $auth = Auth::instance();
        $account = $data['mobile'];
        $password = $data['password'];
        if (!$account || !$password) {
            return ['code'=>0,'msg'=>'无效参数','data'=>''];
        }
        $ret = $auth->login($account, $password, 1);
        if ($ret) {
            $data = $auth->getUserinfo();

            return ['code'=>1,'msg'=>'登录成功','data'=>$data];
        } else {
            return ['code'=>0,'msg'=>$auth->getError(),'data'=>''];
        }
    }

    // 重置密码
    public static function resetpwd($data)
    {
//
        $mobile = $data['mobile'];
        $newpassword = $data['password'];
        $confirmpw = $data['confirmpw'];
        $captcha = $data['code'];
        if (!$newpassword || !$captcha) {
            return ['code'=>0,'msg'=>'无效参数','data'=>''];
        }

        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            return ['code'=>0,'msg'=>'密码必须为6到30个字符','data'=>''];
        }
        if ($newpassword != $confirmpw) {
            return ['code'=>0,'msg'=>'两次密码不一致','data'=>''];
        }

        if (!Validate::regex($mobile, "^1\d{10}$")) {
            return ['code'=>0,'msg'=>'手机号格式不正确','data'=>''];
        }
        $user = \app\common\model\User::where(['mobile' => $mobile,'group_id'=>1])->find();
        if (!$user) {
            return ['code'=>0,'msg'=>'用户信息不存在','data'=>''];
        }
        $status = $user->status;
        if ($status == 'hidden') {
            return ['code'=>0,'msg'=>'账号已锁定','data'=>''];
        }
        if($status == 'logoff'){
            return ['code'=>0,'msg'=>'账号已注销','data'=>''];
        }
        $ret = Sms::check($mobile, $captcha, 'resetpwd');
//        $ret = true;
        if (!$ret) {
            return ['code'=>0,'msg'=>'验证码错误','data'=>''];
        }
        Sms::flush($mobile, 'resetpwd');
        //模拟一次登录
//        $auth = Auth::instance();
//        $auth->direct($user->id);

        $salt = Random::alnum();
        $user->password = md5(md5($newpassword) . $salt);
        $ret = $user->save(['loginfailure' => 0, 'password' => $user->password, 'salt' => $salt]);
        if ($ret) {
            return ['code'=>1,'msg'=>'操作成功','data'=>['password' => $user->password, 'salt' => $salt]];
        } else {
            return ['code'=>1,'msg'=>'操作失败','data'=>''];
        }
    }

    // 获取个人信息
    public static function getUserInfo($data)
    {
        $auth = Auth::instance();
        $userInfo = $auth->getUserinfo();
        $userInfo['coupon_number'] = \app\admin\model\CouponUser::where(['user_id'=>$auth->id,'status'=>1])->count();
        // 是否开通车商VIP
        $car_vip = \app\admin\model\UserCarView::where(['user_id'=>$auth->id])->find();
        if($car_vip){
            if($car_vip['is_vip']){
                $userInfo['car_vip'] = 1;
                $userInfo['viptime'] = date('Y-m-d H:i:s',$car_vip['viptime']);
            }else{
                $userInfo['car_vip'] = 0;
                $userInfo['viptime'] = '';
            }
        }else{
            $userInfo['car_vip'] = 0;
            $userInfo['viptime'] = '';
        }
        // 是否车商认证
        $result = \app\admin\model\CarDealerCertification::where(['user_id'=>$auth->id,])->order('id desc')->find();
        if($result){
            $userInfo['is_car_dealer'] = $result['status'];
        }else{
            $userInfo['is_car_dealer'] = 100;
        }

        return ['code'=>1,'msg'=>'获取成功','data'=>$userInfo];
    }

    /**
     * 积分明细
     */
    public static function getScoreList($data)
    {
        $auth = Auth::instance();
        $limit = isset($data['limit']) ? $data['limit'] : 10;
        $user_id = $auth->id;
        $list = \app\common\model\ScoreLog::where(['user_id'=>$user_id])->field('id,score,memo,FROM_UNIXTIME(createtime,"%Y-%m-%d %H:%i:%s") as createtime_text')->order('createtime DESC')->paginate($limit);

        return ['code'=>1,'msg'=>'获取成功','data'=>['score'=>$auth->score,'list'=>$list]];
    }

    /**
     * 我的优惠劵
     */
    public static function getCouponList($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $type = isset($data['type']) ? $data['type'] : '';// install-安装  repair-维修 shops-商城
        $money = isset($data['money']) ? $data['money'] : 0;
        $where['user_id'] = $user_id;
        $where['status'] = 1;

        $list = \app\admin\model\CouponUser::where($where)
            ->field('id,coupon_id,FROM_UNIXTIME(expiretime,"%Y-%m-%d %H:%i:%s") as expiretime_text')
            ->order('createtime DESC')->select();
        if($list){
            foreach ($list as &$row){
                $coupon = \app\admin\model\Coupon::where(['id'=>$row['coupon_id']])->find();
                if($type && $coupon['type'] == 1 && $money < $coupon['reduction_amount']) {
                    $row['available'] = 0;
                    $row['reason'] = '订单金额不足';
                }elseif($type == 'install' && in_array($coupon['type'],[2,3])){
                    $row['available'] = 0;
                    $row['reason'] = '订单类型不符';
                }elseif($type == 'repair' && $coupon['type'] == 3){
                    $row['available'] = 0;
                    $row['reason'] = '订单类型不符';
                }elseif($type == 'shops' && $coupon['type'] == 2){
                    $row['available'] = 0;
                    $row['reason'] = '订单类型不符';
                }else{
                    $row['available'] = 1;
                }

                $row['coupon_type'] = $coupon['type']; // 类型：1满减 2维修全免 3专属商品全额抵用
                $row['coupon_name'] = $coupon['title'];
                $row['reduction_amount'] = $coupon['reduction_amount'];
                $row['discount_amount'] = $coupon['discount_amount'];
            }
        }else{
            $list = [];
        }
        return ['code'=>1,'msg'=>'获取成功','data'=>$list];
    }

    // 重置密码
    public static function changepwd($data)
    {
//
        $mobile = $data['mobile'];
        $newpassword = $data['password'];
        $captcha = $data['code'];
        if (!$newpassword || !$captcha) {
            return ['code'=>0,'msg'=>'无效参数','data'=>''];
        }

        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            return ['code'=>0,'msg'=>'密码必须为6到30个字符','data'=>''];
        }

        if (!Validate::regex($mobile, "^1\d{10}$")) {
            return ['code'=>0,'msg'=>'手机号格式不正确','data'=>''];
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if (!$user) {
            return ['code'=>0,'msg'=>'用户信息不存在','data'=>''];
        }
        $status = $user->status;
        if ($status == 'hidden') {
            return ['code'=>0,'msg'=>'账号已锁定','data'=>''];
        }
        if($status == 'logoff'){
            return ['code'=>0,'msg'=>'账号已注销','data'=>''];
        }
//        $ret = Sms::check($mobile, $captcha, 'resetpwd');
        $ret = true;
        if (!$ret) {
            return ['code'=>0,'msg'=>'验证码错误','data'=>''];
        }
        Sms::flush($mobile, 'resetpwd');
        //模拟一次登录
        $auth = Auth::instance();
        $auth->direct($user->id);

        $salt = Random::alnum();
        $user->password = md5(md5($newpassword) . $salt);
        $ret = $user->save(['loginfailure' => 0, 'password' => $user->password, 'salt' => $salt]);
        if ($ret) {
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        } else {
            return ['code'=>1,'msg'=>'操作失败','data'=>''];
        }
    }

    // 我的账单
    public static function getBillList($data)
    {
        $auth = Auth::instance();
        $limit = isset($data['limit']) ? $data['limit'] : 10;
        $user_id = $auth->id;
        $list = \app\admin\model\ShopOrder::where(['user_id'=>$user_id,'paid'=>1,'payamount'=>['>',0], 'status'=>['in','0,1,2,3']])->field('id,payamount,createtime')->order('createtime DESC')->paginate($limit)->each(function ($row){
            $item = \app\admin\model\ShopOrderItem::where(['order_id'=>$row['id']])->field('goods_name')->find();
            $row['goods_name'] = $item['goods_name'];
            $row['createtime_text'] = date('Y-m-d H:i:s',$row['createtime']);
        });
        return ['code'=>1,'msg'=>'获取成功','data'=>$list];
    }








    // 修改个人信息
    public static function editUserProfile($data)
    {
        $auth = Auth::instance();
        $user = $auth->getUser();
        $nickname = $data['nickname'];
        $avatar = $data['avatar'];

        if ($nickname) $user->nickname = $nickname;
        if ($avatar) $user->avatar = $avatar;
        if(!$nickname && !$avatar) return ['code'=>0,'msg'=>'没有更新任何数据','data'=>''];
        $user->save();
        return ['code'=>1,'msg'=>'操作成功','data'=>''];
    }

    // 验证码登录
    public static function mobilelogin($data)
    {
        $auth = Auth::instance();
        $mobile = $data['mobile'];
        $captcha = $data['code'];

        if (!$mobile || !$captcha) {
            return ['code'=>0,'msg'=>'无效参数','data'=>''];
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            return ['code'=>0,'msg'=>'手机号格式不正确','data'=>''];
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            return ['code'=>0,'msg'=>'验证码错误','data'=>''];
        }

        if( isset($data['pid']) && $data['pid']){
            //实例化Hashids类
            $hashids = Hashids::instance(6,'91travel');//6为邀请码的长度，mackie为加盐密钥
            //解密
            $pid = $hashids->decode($data['pid']);
        }else{
            $pid = 0;
        }

        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status == 'hidden') {
                return ['code'=>0,'msg'=>'账号已锁定','data'=>''];
            }
            if ($user->status == 'logoff') {
                return ['code'=>0,'msg'=>'账号已注销','data'=>''];
            }
            //如果已经有账号则直接登录
            $ret = $auth->direct($user->id);
        } else {

            $invite_code = create_invite_code();

            $ret = $auth->register($mobile, '123456', '', $mobile, ['invite_code'=>$invite_code,'pid'=>$pid]);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');

            // 发邀请奖励
            if($pid){
                $bonus = Config::get('site.invite_reward');
                if($bonus){
                    $res = \app\common\model\User::bonus($bonus,$pid,'邀请注册奖励');
//                    return $res;
                }
            }

            $data = $auth->getUserinfo();
            return ['code'=>1,'msg'=>'登录成功','data'=>$data];
        } else {
            return ['code'=>0,'msg'=>$auth->getError(),'data'=>''];
        }
    }

    // 注销账号
    public static function logoff()
    {
        $auth = Auth::instance();
        $user = $auth->getUser();
        $user->status = 'logoff';
        // 修改状态
        $user->save();
        // 退出登录
        $auth->logout();
        return ['code'=>1,'msg'=>'注销成功','data'=>''];
    }

    // 退出登录
    public static function logout()
    {
        $auth = Auth::instance();
        $auth->logout();
        return ['code'=>1,'msg'=>'退出成功','data'=>''];
    }
}